package com.contract.commonlib.base

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import cn.woochen.comlib.config.IBaseView
import cn.woochen.comlib.loadinglayout.EmptyCallBack
import cn.woochen.comlib.loadinglayout.ErrorCallback
import cn.woochen.comlib.loadinglayout.LoadingCallBack
import cn.woochen.comlib.loadinglayout.LoadingHasContentCallBack
import com.contract.commonlib.R
import com.contract.commonlib.refresh.MyRefreshLayout
import com.contract.commonlib.refresh.NoMoreDataFootView
import com.contract.commonlib.util.ActivityUtil
import com.contract.commonlib.util.DisplayUtils
import com.contract.commonlib.util.StatusBarUtil
import com.kingja.loadsir.core.LoadService
import com.kingja.loadsir.core.LoadSir
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

/**
 * activity基类(勿修改)
 */
abstract class BaseActivity<DB : ViewDataBinding, VM : BaseViewModel> : AppCompatActivity(),
    IBaseView {

    protected val mContext by lazy {
        this
    }

    protected lateinit var mBinding: DB
        private set

    protected lateinit var mViewModel: VM

    protected lateinit var loadService: LoadService<*>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ActivityUtil.addActivity(this)
        mBinding = DataBindingUtil.setContentView(this, setContentView())
        mViewModel = createViewModel()
        loadService = LoadSir.getDefault().register(loadingLayout()) {
            onReload()
        }
        initStatusBar()
        DisplayUtils.initScreen(this)
        registerNecessaryObserver()
        initListener()
        initData()
        initRefresh()
    }

    protected open fun initStatusBar(){
        mBinding.root.fitsSystemWindows = true
        StatusBarUtil.setWindowStatusBarColor(mContext,R.color.white)
        setStatusBarStyle(false)
    }

    protected open fun setFullScreenStatusBar(){
        mBinding.root.fitsSystemWindows = false
        StatusBarUtil.setStatusBarFullTransparent(this)
    }

    protected open fun onReload() {}
    protected open fun initRefresh() {}
    override fun onDestroy() {
        ActivityUtil.removeActivity(this)
        super.onDestroy()

    }

    private fun createViewModel(): VM {
        return ViewModelProvider(this)
            .get(getVmClazz(this))
    }

    /**
     * 获取任意对象的泛型信息，返回一个继承了BaseViewModel的字节码对象
     */
    private fun getVmClazz(obj: Any): Class<VM> {
        var cls: Class<*>? = obj.javaClass
        var vmClass: Class<VM>? = null
        while (vmClass == null && cls != null) {
            vmClass = getVMClass(cls)
            cls = cls.superclass
        }
        if (vmClass == null) {
            vmClass = BaseViewModel::class.java as Class<VM>
        }
        return vmClass
    }

    private fun getVMClass(cls: Class<*>): Class<VM>? {
        val type: Type? = cls.genericSuperclass
        if (type is ParameterizedType) {
            val types: Array<Type> = type.actualTypeArguments
            for (t in types) {
                if (t is Class<*>) {
                    val vmClass = t
                    if (BaseViewModel::class.java.isAssignableFrom(vmClass)) {
                        return vmClass as Class<VM>
                    }
                } else if (t is ParameterizedType) {
                    val rawType: Type = t.rawType
                    if (rawType is Class<*>) {
                        val vmClass = rawType
                        if (BaseViewModel::class.java.isAssignableFrom(vmClass)) {
                            return vmClass as Class<VM>
                        }
                    }
                }
            }
        }
        return null
    }

    /**
     * 设置加载布局区域(默认为activity对应xml的根布局)
     */
    protected open fun loadingLayout(): Any {
        return this
    }

    /**
     * 注册必要的观察者
     */
    private var isShowContent: Boolean = true
    protected open fun registerNecessaryObserver() {
        mViewModel.loadingChange.showDialog.observe(this, Observer {
            isShowContent = it
            showLoading(it)
        })
        mViewModel.loadingChange.dismissDialog.observe(this, Observer {
            if (it) {
                showContent()
            } else {
                if (isShowContent){
                    showContent()
                }else{
                    showError()
                }
            }
        })
    }


    /**
     * 设置布局文件
     * @return 布局文件id
     */
    protected abstract fun setContentView(): Int

    /**
     * 初始化监听器
     */
    protected open fun initListener() {}

    /**
     * 网络请求数据
     */
    protected open fun requestData() {}

    /**
     * 初始化数据
     */
    abstract fun initData()


    //  --------------statusbar start--------------
    private var systemType = 0

    /**
     * 设置状态栏风格
     * @param isDark 默认为true，暗色风格，文字为白色(默认)
     */
    fun setStatusBarStyle(isDark: Boolean) {
        if (isDark) {
            StatusBarUtil.StatusBarDarkMode(this, systemType)
        } else {
            systemType = StatusBarUtil.StatusBarLightMode(this)
        }
    }

    //  --------------statusbar end--------------

    //--------------loadingLayout start--------------
    override fun showContent() {
        loadService.showSuccess()
    }

    override fun showEmpty() {
        loadService.showCallback(EmptyCallBack::class.java)
    }

    protected open val footView by lazy {
        NoMoreDataFootView(mContext)
    }

    override fun showLoading(showContent: Boolean,content:String) {
        if (showContent) {
            loadService.showCallback(LoadingHasContentCallBack(content)::class.java)
        } else {
            loadService.showCallback(LoadingCallBack::class.java)
        }
    }

    override fun showError() {
        loadService.showCallback(ErrorCallback::class.java)
    }
    //--------------loadingLayout end--------------

    override fun onBackPressed() {
        if (!isFinishing) {
            back()
        }
    }

    protected open fun back() {
        finish()
    }

    open fun beginRefreshing(bgRefres: MyRefreshLayout) {
        bgRefres.autoRefresh()
    }

    open fun endRefreshing(bgRefres: MyRefreshLayout) {
        bgRefres.finishRefresh()
    }

    open fun endLoadingMore(bgRefres: MyRefreshLayout) {
        bgRefres.finishLoadMore()
    }

    open fun setDataLoadFinish(pageNum: Int, size: Int, bgRefresh: MyRefreshLayout) {
        if (pageNum == 1) {
            if (size > 0) {
                footView.footViewState(NoMoreDataFootView.FOOT_HIDE)
            } else {
                footView.footViewState(NoMoreDataFootView.FOOT_NO_DATA)
                bgRefresh.finishLoadMoreWithNoMoreData()
            }
            endRefreshing(bgRefresh)
        } else {
            if (size <= 0) {
                footView.footViewState(NoMoreDataFootView.FOOT_NO_MORE)
                bgRefresh.finishLoadMoreWithNoMoreData()
            } else {
                footView.footViewState(NoMoreDataFootView.FOOT_HIDE)
                endLoadingMore(bgRefresh)
            }
        }
    }

    open fun endLoad(pageNum: Int, bgRefresh: MyRefreshLayout){
        if (pageNum==1){
            endRefreshing(bgRefresh)
        }else{
            endLoadingMore(bgRefresh)
        }
    }
    fun goLaunch(context: Context, tClass: Class<*>?) {
        val intent = Intent(context, tClass)
        context.startActivity(intent)
    }
}